#! -*- coding:utf-8 -*-
import os
import json
import logging
import requests
from datetime import datetime
from common.pay.model import Pay, PAY_STATUS
from common.utils import tz
from common.utils.bot import ADMIN

from django.core.management.base import BaseCommand


_LOGGER = logging.getLogger('alipay')

_SEND_TEXT_API = 'https://bot.potato.im:5423/8026170:CeywfHBsJqh1G1Gn6l07YXXc/sendTextMessage'

NOTIFY_UIDS = [
    ADMIN.MIKE,
    ADMIN.OWEN,
    ADMIN.ARNO,
    ADMIN.KAEL,
    ADMIN.AMY,
]


def send_text_msg(chat_type, chat_id, chat_text):
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    post_data = {
        "chat_type": chat_type,
        "chat_id": chat_id,
        "text": chat_text,
        "markdown": True,
    }
    response = requests.post(_SEND_TEXT_API, data=json.dumps(post_data,separators=(',',':')), headers=headers, timeout=5)


class Command(BaseCommand):

    def handle(self, **kwargs):
        last_pay = Pay.query.filter(Pay.status == PAY_STATUS.DONE) \
            .order_by(Pay.updated_at.desc()).first()
        nowts = tz.now_ts()
        last_ts = tz.to_ts(last_pay.updated_at)
        if nowts - last_ts > 600:
            title = u"Witch 充值异常"
            body = u"Witch 超过10分钟没有成功充值, %s" % tz.local_now()
            for uid in NOTIFY_UIDS:
                send_text_msg(1, uid, u'**{}**\n**{}**\n**{}**'.format(title, title, body))
